package com.ruoyi.framework.config.properties;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * druid 配置属性
 * 
 * @author ruoyi
 */
@Slf4j
@Configuration
public class DruidProperties
{
    @Value("${spring.datasource.druid.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.druid.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.druid.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.druid.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.druid.connectTimeout}")
    private int connectTimeout;

    @Value("${spring.datasource.druid.socketTimeout}")
    private int socketTimeout;

    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}")
    private int maxEvictableIdleTimeMillis;

    @Value("${spring.datasource.druid.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.druid.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.druid.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.druid.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.druid.connectProperties}")
    private String connectProperties;

    @Value("${spring.datasource.druid.filters}")
    private String filters;

    @Value("${spring.datasource.druid.filter.stat.log-slow-sql}")
    private boolean logSlowSql;
    @Value("${spring.datasource.druid.filter.stat.merge-sql}")
    private boolean mergeSql;
    @Value("${spring.datasource.druid.filter.stat.slow-sql-millis}")
    private long slowSqlMill;

    @Value("${spring.datasource.druid.filter.wall.log-violation}")
    private boolean logViolation;
    @Value("${spring.datasource.druid.filter.wall.throw-exception}")
    private boolean throwException;

    @Value("${spring.datasource.druid.filter.wall.config.multi-statement-allow}")
    private boolean multiStatementAllow;
    @Value("${spring.datasource.druid.filter.wall.config.none-base-statement-allow}")
    private boolean noneBaseStatementAllow;
    @Value("${spring.datasource.druid.filter.wall.config.delete-allow}")
    private boolean deleteAllow;
    @Value("${spring.datasource.druid.filter.wall.config.drop-table-allow}")
    private boolean dropTableAllow;
    @Value("${spring.datasource.druid.filter.wall.config.select-all-column-allow}")
    private boolean selectAllColumnAllow;

    @Value("${spring.datasource.druid.filter.slf4j.statement-log-error-enabled}")
    private boolean statementLogErrorEnabled;
    @Value("${spring.datasource.druid.filter.slf4j.statement-create-after-log-enabled}")
    private boolean statementCreateAfterLogEnabled;
    @Value("${spring.datasource.druid.filter.slf4j.statement-close-after-log-enabled}")
    private boolean statementCloseAfterLogEnabled;
    @Value("${spring.datasource.druid.filter.slf4j.result-set-open-after-log-enabled}")
    private boolean resultSetOpenAfterLogEnabled;
    @Value("${spring.datasource.druid.filter.slf4j.result-set-close-after-log-enabled}")
    private boolean resultSetCloseAfterLogEnabled;

    public DruidDataSource dataSource(DruidDataSource datasource)
    {
        /** 配置初始化大小、最小、最大 */
        datasource.setInitialSize(initialSize);
        datasource.setMaxActive(maxActive);
        datasource.setMinIdle(minIdle);

        /** 配置获取连接等待超时的时间 */
        datasource.setMaxWait(maxWait);

        /** 配置驱动连接超时时间，检测数据库建立连接的超时时间，单位是毫秒 */
        datasource.setConnectTimeout(connectTimeout);

        /** 配置网络超时时间，等待数据库操作完成的网络超时时间，单位是毫秒 */
        datasource.setSocketTimeout(socketTimeout);

        /** 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒 */
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

        /** 配置一个连接在池中最小、最大生存的时间，单位是毫秒 */
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);

        /**
         * 用来检测连接是否有效的sql，要求是一个查询语句，常用select 'x'。如果validationQuery为null，testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
         */
        datasource.setValidationQuery(validationQuery);
        /** 建议配置为true，不影响性能，并且保证安全性。申请连接的时候检测，如果空闲时间大于timeBetweenEvictionRunsMillis，执行validationQuery检测连接是否有效。 */
        datasource.setTestWhileIdle(testWhileIdle);
        /** 申请连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能。 */
        datasource.setTestOnBorrow(testOnBorrow);
        /** 归还连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能。 */
        datasource.setTestOnReturn(testOnReturn);

        /** 为数据库密码提供加密功能 */
        datasource.setConnectionProperties(connectProperties);

//        try {
//            datasource.setFilters(filters);
//        } catch (SQLException e) {
//            log.error("datasource.setFilters异常，异常信息为:{{}}", e.getMessage());
//        }

        datasource.setProxyFilters(Arrays.asList(statFilter(),logFilter(),wallFilter()));
        return datasource;
    }

    @Bean
    public StatFilter statFilter() {
        StatFilter statFilter = new StatFilter();
        statFilter.setSlowSqlMillis(slowSqlMill);
        statFilter.setLogSlowSql(logSlowSql);
        statFilter.setMergeSql(mergeSql);
        return statFilter;
    }

    @Bean
    public Slf4jLogFilter logFilter() {
        Slf4jLogFilter slf4jLogFilter = new Slf4jLogFilter();
        slf4jLogFilter.setStatementLogErrorEnabled(statementLogErrorEnabled);
        slf4jLogFilter.setStatementCreateAfterLogEnabled(statementCreateAfterLogEnabled);
        slf4jLogFilter.setStatementCloseAfterLogEnabled(statementCloseAfterLogEnabled);
        slf4jLogFilter.setResultSetOpenAfterLogEnabled(resultSetOpenAfterLogEnabled);
        slf4jLogFilter.setResultSetCloseAfterLogEnabled(resultSetCloseAfterLogEnabled);
//        filter.setResultSetLogEnabled(false);
//        filter.setConnectionLogEnabled(false);
//        filter.setStatementParameterClearLogEnable(false);
//        filter.setStatementParameterSetLogEnabled(false);
//        filter.setStatementPrepareAfterLogEnabled(false);
        return slf4jLogFilter;
    }

    @Bean
    public WallFilter wallFilter() {
        WallFilter wallFilter = new WallFilter();
        wallFilter.setLogViolation(logViolation);
        wallFilter.setThrowException(throwException);
        wallFilter.setConfig(wallConfig());
        return wallFilter;
    }

    @Bean
    public WallConfig wallConfig() {
        WallConfig wallConfig = new WallConfig();
        // 是否允许执行 DELETE 语句
        wallConfig.setDeleteAllow(deleteAllow);
        // 是否允许删除表
        wallConfig.setDropTableAllow(dropTableAllow);
        //允许一次执行多条语句
        wallConfig.setMultiStatementAllow(multiStatementAllow);
        wallConfig.setNoneBaseStatementAllow(noneBaseStatementAllow);
        wallConfig.setSelectAllColumnAllow(selectAllColumnAllow);
        return wallConfig;
    }
}
